package com.gzk.hrm.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.gzk.hrm.domain.Login;
import com.gzk.hrm.dto.LoginMealDto;
import com.gzk.hrm.mapper.LoginMapper;
import com.gzk.hrm.service.ILoginService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gzk.hrm.util.AssertUtils;
import com.gzk.hrm.util.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author jake.Chen
 * @since 2022-02-10
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Value("${hrm.httpClientUrl}")
    private String httpClientUrl;

    @Override
    @Transactional
    public void saveLoginMeal(LoginMealDto dto) {
        loginMapper.saveLoginMeal(dto);
    }

    /**
     * 登录
     * @param login
     * @return 返回的token
     */
    @Override
    public Map<String, Object> login(Login login) {
        String username = login.getUsername();
        String password = login.getPassword();
        //根据用户名查询数据库
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login1 = selectOne(wrapper);
        //校验用户是否存在
        AssertUtils.isNotNull(login1, "非法的用户！");

        //获取client_id和secret
        String clientId = login1.getClientId();
        String clientSecret = "123";

        //拼接url
        String url = String.format(httpClientUrl, clientId, clientSecret, username, password);

        //发送请求
        Map<String, Object> result = HttpClients.doPost(url);
        AssertUtils.isNull(result.get("error"), "账号或者密码错误！");
        return result;
    }
}
